/**
 * 团课
 */

app.controller('leagueCtrl', function ($scope, $http, $location, $rootScope, $stateParams, $ionicTabsDelegate, dialogsManager) {

    $scope.selectDate = newDate();
    //团课所有课程
    var url = 'http://qa.aixingfu.net/v1/api-class/get?venueId=' + $rootScope.globalInfo.user.venueId;
    $scope.allCourses = function () {
        $http({
            url: url,
            method: 'GET',
        }).success(function (date) {
            $scope.date = date;
            for (var i in date) {
                if (date.hasOwnProperty(i)) {
                    var element = date[i];
                    for (var q in element.list) {
                        if (element.list.hasOwnProperty(q)) {
                            var items = element.list[q];
                        }
                    }
                }
            }
        }).error(
            function (data) {
                console.log(data);
                $scope.showMessage = function () {
                    dialogsManager.showMessage('系统错误,请联系工作人员');
                }
                $scope.showMessage();
            }
            );
    }
    $scope.allCourses();

    //关闭筛选下拉
    $(function () {
        $('.listTabs').on('click', function () {
            $('#courseSelect').addClass('disNone');
            $('#privateCourseSelect').addClass('disNone');
        })
    })

    $scope.doRefresh = function () {
        $http.get('http://qa.aixingfu.net/v1/api-class/get?venueId=' + $rootScope.globalInfo.user.venueId)
            .success(function (newItems) {
                $scope.date = newItems;
            })
            .finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
            });
    };
    //团课课种分类
    var urlCourse = 'http://qa.aixingfu.net/v1/api-class/get-course-data?type=2' + '&venueId=' + $rootScope.globalInfo.user.venueId;
    $scope.getClassData = function () {
        $http({
            url: url,
            method: 'GET',
        }).success(function (date) {
            $scope.date = date;
            for (var i in date) {
                if (date.hasOwnProperty(i)) {
                    var element = date[i];
                    for (var q in element.list) {
                        if (element.list.hasOwnProperty(q)) {
                            var items = element.list[q];
                        }
                    }
                }
            }
        }).error(
            function (data) {
                console.log(data);
                $scope.showMessage = function () {
                    dialogsManager.showMessage('系统错误,请联系工作人员');
                }
                $scope.showMessage();
            }
            );
    };

    //课种分类
    $scope.getCourseData = function () {
        $http({
            url: urlCourse,
            method: 'GET',
        }).success(function (course) {
            $scope.classFication = course;
        }).error(
            function (course) {
                console.log(cursor);
                $scope.showMessage = function () {
                    dialogsManager.showMessage('系统错误,请联系工作人员');
                }
                $scope.showMessage();
            }
            );
    }


    $scope.getClassData();
    $scope.getCourseData();
    $scope.onclick = function (id, date, type) {
        console.log(type)
        if (type == false) {
            $scope.showMessage = function () {
                dialogsManager.showMessage('课程已经开始，不能预约~ ');
            }
            $scope.showMessage();
            return 
        }
        $rootScope.ids = id;
        $rootScope.dates = date;
        location.href = '#/tab/league/' + id + '/' + date
    }

    $scope.startDate = function () {
        alert('sadsa')
    }
    $scope.data = { result: "" };

    //定义回调函数返回日历时间
    $scope.callback = function (value) {
        $('#courseSelect').addClass('disNone');
        var url1 = 'http://qa.aixingfu.net/v1/api-class/get?date=' + value + '&venueId=' + $rootScope.globalInfo.user.venueId;
        $http({
            url: url1,
            method: 'GET',
        }).success(function (date) {
            //如果返回的数据为空  执行下面的
            if (date == '') {
                var message = '您好！' + value + '没有课程';
                $scope.showMessage = function () {
                    dialogsManager.showMessage(message);
                }
                $scope.showMessage();
            }
            //不为空执行下面的 
            else if (date != '') {
                $scope.date = date;
            }
        }).error(
            function (data) {
                console.log(data);
                $scope.showMessage = function () {
                    dialogsManager.showMessage('系统错误,请联系工作人员');
                }
                $scope.showMessage();
            })
        return false;
    }
    //点击显示课程分类列表
    $scope.leagueCourse = function () {
        $('#courseSelect').toggleClass('disNone')
    }
    //关闭课程分类
    $scope.closeCourseSelect = function () {
        $('#courseSelect').addClass('disNone');
    }
    //获取全部课程
    $scope.allLeagueCourse = function () {
        $('#courseSelect').addClass('disNone');
        $scope.allCourses();
    }

    //选中课程分类中课程后触发的事件
    $scope.courseSelected = function (id) {
        for (var i = 0; i < $scope.classFication.length; i++) {
            if (parseInt($scope.classFication[i].id) == parseInt(id)) {
                var url2 = 'http://qa.aixingfu.net/v1/api-class/get?course=' + id + '&venueId=' + $rootScope.globalInfo.user.venueId;
                $http({
                    url: url2,
                    method: 'GET',
                }).success(function (date) {
                    if (date == '') {
                        var message = '不好意思，还没有课程';
                        $scope.showMessage = function () {
                            dialogsManager.showMessage(message);
                        }
                        $scope.showMessage();
                    } else if (date != '') {
                        $scope.date = date;
                    }
                }).error(
                    function (data) {
                        console.log(data);
                        $scope.showMessage = function () {
                            dialogsManager.showMessage('系统错误,请联系工作人员');
                        }
                        $scope.showMessage();
                    }
                    );
            }
        }
        $('#courseSelect').addClass('disNone')
    }
});
/**
 * 团课详情页面
 */
app.controller('detailsCtrl', function ($scope, $rootScope, $stateParams, $http, $ionicHistory, $state, dialogsManager, Storage) {
    //返回上一页
    $scope.back = function () {
        $ionicHistory.goBack();
    }
    var url = 'http://qa.aixingfu.net/v1/api-class/get-detail?id=' + $rootScope.ids + '&memberId=' + $rootScope.globalInfo.user.ids;

    $http({
        url: url,
        method: 'GET',
    }).success(function (date) {
        $scope.items = date;
        $rootScope.details = date;

        $rootScope.itemsCoadchId = $scope.items.coach_id;
        $rootScope.itemsVenueId = $scope.items.venue_id;

    }).error(
        function (data) {
            console.log(data);
            $scope.showMessage = function () {
                dialogsManager.showMessage('系统错误,请联系工作人员');
            }
            $scope.showMessage();
        }
        );
    /**
     * 场馆
     */
    $scope.venueDetailsClick = function (id, date) {
        location.href = '#/tab/league/:' + $rootScope.ids + '/' + $rootScope.dates + '/venueDetails';
    }
    /**
     * 地图
     */
    $scope.venueMapClick = function (id, date) {
        location.href = '#/tab/league/:' + $rootScope.ids + '/' + $rootScope.dates + '/map';
    }
    /**
     * 教练
     */
    $scope.coachDetailsClick = function () {
        location.href = '#/tab/league/:' + $rootScope.ids + '/' + $rootScope.dates + '/coach';
    }
    /**
     * 约课n
     */
    $scope.buttonClick = function () {
        if ($rootScope.details.isAboutClass == true) {
            $('#leagueDetailsButton').attr('disabled', 'disabled')
            $scope.showMessage = function () {
                dialogsManager.showMessage("您已经预约过");
            }
            $scope.showMessage();
            return;
        }
        if ($rootScope.details.isCanClass == false) {
            $('#leagueDetailsButton').attr('disabled', 'disabled')
            $scope.showMessage = function () {
                dialogsManager.showMessage("您现在无法预约此课程！");
            }
            $scope.showMessage();
            return;
        }
        if ($rootScope.details.limitTime == false) {
            $('#leagueDetailsButton').attr('disabled', 'disabled')
            $scope.showMessage = function () {
                dialogsManager.showMessage("快要开课了,您下次再预约吧！");
            }
            $scope.showMessage();
            return;
        }
        location.href = '#/tab/league/:' + $rootScope.ids + '/' + $rootScope.dates + '/appointment';
    }
});

// 场馆详情
app.controller('venueDetailsCtrl', function ($scope, $rootScope, $stateParams, $http, $ionicHistory, dialogsManager) {
    var url = 'http://qa.aixingfu.net/v1/api-venue/get-venue-detail?id=' + $rootScope.itemsVenueId;
    $http({
        url: url,
        method: 'GET',
    }).success(function (date) {
        $scope.items = date;
    }).error(
        function (data) {
            console.log(data);
            $scope.showMessage = function () {
                dialogsManager.showMessage('系统错误,请联系工作人员');
            }
            $scope.showMessage();
        }
        );
    $scope.back = function () {
        $ionicHistory.goBack()
    }
})

// 教练详情
app.controller('coachCtrl', function ($scope, $rootScope, $stateParams, $http, dialogsManager, $ionicHistory) {
    $scope.back = function () {
        $ionicHistory.goBack();
    }
    var url = 'http://qa.aixingfu.net/v1/api-coach/get-coach-detail?id=' + $rootScope.itemsCoadchId + '&callback=JSON_CALLBACK';
    $http({
        url: url,
        method: 'GET',
    }).success(function (date) {
        $scope.items = date;
    }).error(
        function (data) {
            console.log(data);
            $scope.showMessage = function () {
                dialogsManager.showMessage('系统错误,请联系工作人员');
            }
            $scope.showMessage();
        }
        );
})


//约课详情
app.controller('appointmentCtrl', function ($scope, $rootScope, $http, $stateParams, $ionicHistory, $state, dialogsManager) {
    //线上接口
    $scope.back = function () {
        $ionicHistory.goBack();
    }
    var url = 'http://qa.aixingfu.net/v1/api-class/get-seat-detail?id=' + $rootScope.ids;
    $http({
        url: url,
        method: 'GET',
    }).success(function (date) {
        $scope.items = date;
    }).error(
        function (data) {
            console.log(data);
            $scope.showMessage = function () {
                dialogsManager.showMessage('系统错误,请联系工作人员');
            }
            $scope.showMessage();
        }
        );
    //选择座位
    var seatNum;
    $scope.seatSelect = function (id, num, type) {

        $scope.memberSeatType = type;
        if ($('.courseSeates').eq(num - 1).hasClass('notSelect') || $('.selectedVip').eq(num - 1).hasClass('notSelect')) {
            return;
        }
        else {
            seatNum = id;
            var numbers = parseInt(seatNum);
            $rootScope.seatID = numbers;
            var $vip = $('.vip');
            if ($scope.memberSeatType == 1 && $rootScope.globalInfo.user.identify == 1) {
                $('.courseSeates').removeClass('selected');
                $('.courseSeates').eq(num - 1).addClass('selected');
                if (!$vip.hasClass('selected')) {
                    $vip.addClass('selectedVip');
                    $vip.removeClass('vip');
                }
            }
            if ($scope.memberSeatType == 2) {
                if ($scope.memberSeatType != $rootScope.globalInfo.user.identify) {
                    $scope.showMessage = function () {
                        dialogsManager.showMessage("不好意思请升级，您的卡");
                    }
                    $scope.showMessage();
                    return
                }
                $('.courseSeates').removeClass('selected');
                $('.courseSeates').eq(num - 1).removeClass('selectedVip');
                $('.courseSeates').eq(num - 1).addClass('selected');
                $('.courseSeates').eq(num - 1).addClass('vip');
                if (!$vip.hasClass('selected')) {
                    $vip.addClass('selectedVip');
                    $vip.removeClass('vip');
                }
            }
        }
    }
    //点击选择上课位置按钮
    $scope.selectButton = function () {

        var url = 'http://qa.aixingfu.net/v1/api-about-record/set-about-record';
        var orderData = {
            classId: $rootScope.ids,
            memberId: $rootScope.globalInfo.user.ids,
            classType: 'group',
            seatId: $rootScope.seatID
        }
        if (orderData.seatId == '' || orderData.seatId == undefined) {
            // alert('请选择座位');
            $scope.showMessage = function () {
                dialogsManager.showMessage('请选择座位');
            }
            $scope.showMessage();

        } else {
            $http({
                method: 'POST',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                data: $.param(orderData)
            }).then(function (success) {
                $ionicHistory.clearCache();
                location.href = '#/tab/league/:' + $rootScope.ids + '/' + $rootScope.dates + '/complete';
            }, function (error) {
                console.log(error);
                $scope.showMessage = function () {
                    dialogsManager.showMessage('系统错误,请联系工作人员');
                }
                $scope.showMessage();
            })
        }
    }
})

app.controller('completeCtrl', function ($scope, $ionicHistory, $rootScope, $stateParams, $state) {
    $scope.backHomepage = function () {
        location.href = '#/tab/league'
    }
})

// 
app.controller('mapCtrl', function ($ionicHistory, $scope) {
    //返回上一页
    $scope.backPrePage = function () {
        $ionicHistory.goBack();

    }

    //创建和初始化地图函数：
    function initMap() {
        createMap();//创建地图
        setMapEvent();//设置地图事件
        addMapControl();//向地图添加控件
        addMarker();//向地图中添加marker
    }


    //创建地图函数：
    function createMap() {
        var map = new BMap.Map("dituContent");//在百度地图容器中创建一个地图
        var point = new BMap.Point(113.676957, 34.763269);//定义一个中心点坐标
        map.centerAndZoom(point, 17);//设定地图的中心点和坐标并将地图显示在地图容器中
        window.map = map;//将map变量存储在全局
    }



    //地图事件设置函数：
    function setMapEvent() {
        map.disableDragging();//禁用地图拖拽事件
        map.disableScrollWheelZoom();//禁用地图滚轮放大缩小，默认禁用(可不写)
        map.disableDoubleClickZoom();//禁用鼠标双击放大
        map.disableKeyboard();//禁用键盘上下左右键移动地图，默认禁用(可不写)
    }

    //地图控件添加函数：
    function addMapControl() {
    }


    //标注点数组
    var markerArr = [{ title: "", content: "我爱运动健身馆大上海城店", point: "113.676957|34.763269", isOpen: 0, icon: { w: 25, h: 25, l: -2, t: 21, x: 6, lb: 5 } }
    ];
    //创建marker
    function addMarker() {
        for (var i = 0; i < markerArr.length; i++) {
            var json = markerArr[i];
            var p0 = json.point.split("|")[0];
            var p1 = json.point.split("|")[1];
            var point = new BMap.Point(p0, p1);
            var iconImg = createIcon(json.icon);
            var marker = new BMap.Marker(point, { icon: myIcon });
            var iw = createInfoWindow(i);
            var label = new BMap.Label(json.title, { "offset": new BMap.Size(json.icon.lb - json.icon.x + 10, -20) });
            marker.setLabel(label);
            map.addOverlay(marker);
            label.setStyle({
                borderColor: "#808080",
                color: "#333",
                cursor: "pointer"
            });

            (function () {
                var index = i;
                var _iw = createInfoWindow(i);
                var _marker = marker;
                _marker.addEventListener("click", function () {
                    this.openInfoWindow(_iw);
                });
                _iw.addEventListener("open", function () {
                    _marker.getLabel().hide();
                })
                _iw.addEventListener("close", function () {
                    _marker.getLabel().show();
                })
                label.addEventListener("click", function () {
                    _marker.openInfoWindow(_iw);
                })
                if (!!json.isOpen) {
                    label.hide();
                    _marker.openInfoWindow(_iw);
                }
            })()
        }
    }
    //创建marker
    function addMarker() {
        for (var i = 0; i < markerArr.length; i++) {
            var json = markerArr[i];
            var p0 = json.point.split("|")[0];
            var p1 = json.point.split("|")[1];
            var point = new BMap.Point(p0, p1);
            var iconImg = createIcon(json.icon);
            var marker = new BMap.Marker(point, { icon: iconImg });
            var iw = createInfoWindow(i);
            var label = new BMap.Label(json.title, { "offset": new BMap.Size(json.icon.lb - json.icon.x + 10, -20) });
            marker.setLabel(label);
            map.addOverlay(marker);
            label.setStyle({
                borderColor: "#808080",
                color: "#333",
                cursor: "pointer"
            });

            (function () {
                var index = i;
                var _iw = createInfoWindow(i);
                var _marker = marker;
                _marker.addEventListener("click", function () {
                    this.openInfoWindow(_iw);
                });
                _iw.addEventListener("open", function () {
                    _marker.getLabel().hide();
                })
                _iw.addEventListener("close", function () {
                    _marker.getLabel().show();
                })
                label.addEventListener("click", function () {
                    _marker.openInfoWindow(_iw);
                })
                if (!!json.isOpen) {
                    label.hide();
                    _marker.openInfoWindow(_iw);
                }
            })()
        }
    }
    //创建InfoWindow
    function createInfoWindow(i) {
        var json = markerArr[i];
        var iw = new BMap.InfoWindow("<b class='iw_poi_title' title='" + json.title + "'>" + json.title + "</b><div class='iw_poi_content'>" + json.content + "</div>");
        return iw;
    }
    //创建一个Icon
    function createIcon(json) {
        var icon = new BMap.Icon("http://map.baidu.com/image/us_mk_icon.png", new BMap.Size(json.w, json.h), { imageOffset: new BMap.Size(-json.l, -json.t), infoWindowOffset: new BMap.Size(json.lb + 5, 1), offset: new BMap.Size(json.x, json.h) })
        return icon;
    }

    initMap();//创建和初始化地图

})




function newDate() {
    var myDate = new Date();
    var Month = myDate.getMonth() + 1;
    return myDate.getFullYear() + '-' + Month + '-' + myDate.getDate()
}



